package org.micro_gzm.v5.core;

import android.opengl.GLES20;
import android.util.Log;

public class GZMShader {
	
	public static int loadShader(int type, String dataIn) {
		
		int shader;
		int[] compiled = new int[1];
		
		//shader object
		shader = GLES20.glCreateShader(type);
		
		if(shader == 0) return 0;
		
		//set shader source
		GLES20.glShaderSource(shader, dataIn);
		
		//compile the shader
		GLES20.glCompileShader(shader);
		
		//check compile status
		GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
		
		if(compiled[0] == 0) {
			Log.d("MG", GLES20.glGetShaderInfoLog(shader));
			GLES20.glDeleteShader(shader);
			return 0;
		}
		
		return shader;
	}
	
	public static int loadProgram(String vShaderDataIn, String fShaderDataIn) {
		
		int vertexShader;
		int fragmentShader;
		int programObject;
		int[] linked = new int[1];
		
		//load vertex and fragment shader
		vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vShaderDataIn);
		if(vertexShader == 0) return 0;
		
		fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fShaderDataIn);
		if(fragmentShader == 0) {
			
			GLES20.glDeleteShader(vertexShader);
			return 0;
		}
		
		//create program object;
		programObject = GLES20.glCreateProgram();
		if(programObject == 0) return 0;
		
		GLES20.glAttachShader(programObject, vertexShader);
		GLES20.glAttachShader(programObject, fragmentShader);
		
		//link program
		GLES20.glLinkProgram(programObject);
		
		//check link status
		GLES20.glGetProgramiv(programObject, GLES20.GL_LINK_STATUS, linked, 0);
		
		if(linked[0] == 0) {
			Log.d("MG", "Error linking program shader");
			Log.d("MG", GLES20.glGetProgramInfoLog(programObject));
			GLES20.glDeleteProgram(programObject);
			
			return 0;
		}
		
		//delete unneeded shader resource
		GLES20.glDeleteShader(vertexShader);
		GLES20.glDeleteShader(fragmentShader);
		
		return programObject;
	}
}
